import json

import requests
from django.http import JsonResponse
from rest_framework.settings import api_settings
from mini_api.models import User
from miniprogram_rpa.settings import WX_APPID, WX_LOGIN_URL, WX_APPSECRET

class WXOpenid(object):

    # 获取 openid
    @staticmethod
    def get_open_id(login_code):
        wx_login_url = WX_LOGIN_URL + "?appid={}&secret={}&js_code={}&grant_type=authorization_code".format(WX_APPID,WX_APPSECRET,login_code)

        res = requests.get(wx_login_url)
        try:
            openid = res.json()['openid']
            session_key = res.json()['session_key']
        except KeyError:
            return 'fail'
        else:
            return openid, session_key

def login_or_create_account(request):
    data = json.loads(request.body)
    print(data)
    openid = data['openid']
    nickname = data['nickname']
    avatar_url = data['avatar_url']
    gender = data['gender']

    try:
        user = User.objects.get(username=openid)
    except Exception:
        user = None

    if user:
        user = User.objects.get(username=openid)
    else:
        user = User.objects.create(
            username=openid,
            password=openid,
            nickname=nickname,
            avatar_url=avatar_url,
            gender=gender
        )

    jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER
    jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER
    payload = jwt_payload_handler(user)
    token = jwt_encode_handler(payload)
    res = {
        'status': 'success',
        'nickname': user.nickname,
        'user_id': user.id,
        'token': token
    }
    return JsonResponse(res)




